package com.boot.config;

import com.rabbitmq.client.ConnectionFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Queue;

@Configuration
@ConfigurationProperties(prefix = "rabbit-info")
public class RabbitMQConfig {
    //定义队列和交换机名称
    public static final String MIRROR_QUEUE = "mirror_queue";
    public static final String MIRROR_EXCHANGE = "mirror_exchange";

    //配置节点连接
    @Bean
    public CachingConnectionFactory  connectionFactory() {
        CachingConnectionFactory factory = new CachingConnectionFactory();
        //配置多节点信息
        factory.setAddresses("192.168.127.129:5672,192.168.127.131:5672,192.168.127.130:5672");
        factory.setUsername("admin");
        factory.setPassword("as123654");
        //自动恢复连接
        factory.setRequestedHeartBeat(30);  //心跳30s
        factory.setConnectionTimeout(3000);  //连接超时3s
        return factory;
    }


    //声明镜像队列
    @Bean
    public org.springframework.amqp.core.Queue mirrorQueue() {
        return QueueBuilder.durable(MIRROR_QUEUE).build();
    }

    @Bean
    public DirectExchange exchange() {
        return new DirectExchange(MIRROR_EXCHANGE);
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(mirrorQueue())
                .to(exchange())
                .with(MIRROR_QUEUE);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMandatory(true);
        return template;
    }
}
